from PIL import Image
import os


def bmpTojpg(file_path):
    for i in range(0, 10):
        for j in range(1, 501):
            newfile_name = str(i) + '_' + str(j) + '.jpg'
            im = Image.open(file_path + '\\' + str(i) + '\\' + str(i) + '_' + str(j) + '.bmp')
            im.save(file_path + '\\' + str(i) + '\\' + newfile_name)


# 删除原来的图片
def delete_bmp(file_path, imageformat):
    for i in range(0, 10):
        command = "del " + file_path + "\\" + str(i) + "\\*." + imageformat
        os.system(command)


def main():
    file_path = "DataSet"
    bmpTojpg(file_path)
    delete_bmp(file_path, "bmp")
#函数说明：将图片转为文本格式
def jpgTotxt(file_path1, file_path2, num1, num2, num3):
#将训练数据集的图片转换为文本格式
    for i in range(0, 10):
        for j in range(num1, num2):
            im = Image.open('DataSet\\' + str(i) + '\\' + str(i) + '_' + str(j) + '.jpg')
            im = im.convert('RGB')
            width = im.size[0]
            height = im.size[1]
            filename = str(i) + '_' + str(j) + '.txt'
            fh = open(file_path1 + filename, 'w')
            for m in range(0, height):
                for n in range(0, width):
                    col = im.getpixel((n, m))#获得图片像素RGB，符合条件写入1， 不符合写入0
                    if (col[0]<=190 and col[1]<=190 and col[2]<=190):
                        fh.write('1')
                    else:
                        fh.write('0')
                fh.write('\n')
            fh.close()
#将测试数据集的图片转换为文本格式
    for i in range(0, 10):
        for j in range(num2, num3):
            im = Image.open('DataSet\\' + str(i) + '\\' + str(i) + '_' + str(j) + '.jpg')
            im = im.convert('RGB')
            width = im.size[0]
            height = im.size[1]
            filename = str(i) + '_' + str(j-400) + '.txt'
            fh = open(file_path2 + filename, 'w')
            for m in range(0, height):
                for n in range(0, width):
                    col = im.getpixel((n, m))
                    if (col[0]<=190 and col[1]<=190 and col[2]<=190):
                        fh.write('1')
                    else:
                        fh.write('0')
                fh.write('\n')
            fh.close()

if __name__ == '__main__':
    m1 = 1; m2 = 401; m3 = 501;
    file_path_1 = 'trainingDigits\\'
    file_path_2 = 'testDigits\\'
    jpgTotxt(file_path_1, file_path_2, m1, m2, m3)